package dao;

import java.util.List;

import hibernate.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import dto.ClienteDTO;
import dto.EnvioDTO;
import entities.ClienteEntity;
import entities.EnvioEntity;
import entities.SucursalEntity;
import entities.VehiculoEntity;

public class EnvioDAO {
	private static EnvioDAO instancia = null;
	private static SessionFactory sf = null;
	
	private EnvioDAO(){}
	
	public static EnvioDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new EnvioDAO();
		} 
		return instancia;
	}
	
	public void grabarEnvio(EnvioEntity envio){
		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(envio);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public void actualizarEnvio(EnvioEntity envio){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(envio);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public EnvioEntity LoadEnvio(int id) 
	{
		Session session = sf.openSession();
		session.beginTransaction();
		EnvioEntity env = (EnvioEntity) session.get(EnvioEntity.class, id);
		session.flush();
		session.getTransaction().commit();
		session.close();
		return env;
	}

	public List<EnvioEntity> enviosPendienteDePago(String cuit) 
	{
		Session session = sf.openSession();
		session.beginTransaction();
		List<EnvioEntity> entList = session.createQuery("select en from EnvioEntity en inner join en.remito r inner join r.cliente cl where cl.id in (select cl.id from EmpresaEntity em inner join em.cuentaCorriente cc where em.CUIT=:cuit and cc.saldo<>0)").setString("cuit", cuit).list();
		session.flush();
		session.getTransaction().commit();
		session.close();
		return entList;
	}

	public boolean obtenerVehiculoDisponible(VehiculoEntity ve) {
		Session session = sf.openSession();
		session.beginTransaction();
		List<VehiculoEntity> entList = session.createQuery("select ve from EnvioEntity ee inner join ee.vehiculo ve where ve.idVehiculo = :id").setParameter("id", ve.getIdVehiculo()).list();
		if(entList.isEmpty())
		{
			session.flush();
			session.getTransaction().commit();
			session.close();
			return true;
		}
		session.flush();
		session.getTransaction().commit();
		session.close();
		return false;
	}
}
